let searchInput = document.querySelector('.header-search input');
searchInput.nextElementSibling.onclick = function() {
	let value = searchInput.value.trim();
	if(value) {
		location.href = '/page/user/buy/want.html?wd=' + value;
	}
}
searchInput.nextElementSibling.nextElementSibling.onclick = function() {
	let value = searchInput.value.trim();
	if(value) {
		location.href = '/page/user/search/list.html?keyword=' + value;
	}
}
/* 格式化日期 */
Date.prototype.format = function(fmt) { 
	let o = {
		"M+" : this.getMonth()+1, //月份
　　　		"d+" : this.getDate(), //日
　　　　	"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
　　　　	"H+" : this.getHours(), //小时
　　　　	"m+" : this.getMinutes(), //分
　　　　	"s+" : this.getSeconds(), //秒
　　　　	"q+" : Math.floor((this.getMonth()+3)/3), //季度
　　　　	"S" : this.getMilliseconds() //毫秒
　　	};
　　	if(/(y+)/.test(fmt)) {
　　　　	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(let k in o) {
　　　		if(new RegExp("("+ k +")").test(fmt))
　　　　		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
	}
	return fmt;
}
/* 留言板选择排序 */
let commentChoose = document.getElementById('commentChoose');
let commentArea = document.getElementById('commentArea');
let commentPublish = commentArea.previousElementSibling;
let hotSort = commentChoose.children[1];
let newSort = commentChoose.children[0];
let data = null;
//请求用户登录状态
let userBar1 = document.getElementById('userBar1');
let userBar2 = document.getElementById('userBar2');
//获取sno和pwd，发送至服务器校验
let value = getCookieValue('userCookie');
//若没有值则为未登录状态
if(!value) {
	userBar1.innerHTML = `<a href="/page/user/login.html">你好，请登录</a>`;
	userBar2.innerHTML = `<a class="ht" href="/page/user/regist.html">立即注册</a>`;
} else {
	// 若有值，传至服务器校验该值的合法性
	let snoValue = value.split('#_TPLAssociation_#')[0];
	let pwdValue = value.split('#_TPLAssociation_#')[1];
	ajax({
		type: 'POST',
		url: '/user/isLogin',
		async: true,
		data: {
			sno: snoValue,
			pwd: pwdValue
		},
		success: function(xhr) {
			let arg = JSON.parse(xhr.responseText);
			data = arg.data;
			if(arg.code == 200 && arg.message == 'success') {
				// 登录成功
				userBar1.innerHTML = `<a class="ht" href="/page/user/space">${data.nickname}</a>`
				userBar2.innerHTML = `<a href="/user/logout?redirectURL=${location.href}">退出</a>`
				commentPublish.innerHTML = `<div class="publish-l">
						<img src="${data.imgPath}" alt="用户头像" />
					</div>
					<div class="publish-m">
						<textarea cols="80" name="msg" rows="5" placeholder="请自觉遵守互联网相关的政策法规，严禁发布色情、暴力、反动的言论" maxlength="500"></textarea>
					</div>
					<button class="publish-submit">发布</button> `;	
				
				/* 发布求购信息文本域效果 */
				let textarea = document.getElementsByTagName('textarea');
				textarea[0].onfocus = focusEvent;
				textarea[0].onblur = blurEvent;
				/* 发布求购信息 */
				let publishSubmit = commentPublish.querySelector('button');
				publishSubmit.onclick = function() {
					let textarea = this.previousElementSibling.children[0];
					let contentStr = textarea.value.trim();
					if(contentStr.length > 0 && publishSubmit.innerText != '发送中') {
						ajax({
							type: 'POST',
							url: '/want/add',
							async: true,
							data: {
								content: encodeURIComponent(contentStr)
							},
							beforeSend: function() {
								publishSubmit.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;';
								publishSubmit.innerText = '发送中';
								textarea.disabled = 'disabled';
							},
							success: function(xhr) {
								// 还原之前的效果
								publishSubmit.style = '';
								publishSubmit.innerText = '发布';
								textarea.disabled = '';
								// 清空留言板的内容
								textarea.value = '';
								let arg2 = JSON.parse(xhr.responseText);
								if(arg2.code == 3020) {
									location.href = '/page/user/login.html';
								} else if(arg2.code == 300) {
									toast('请输入求购内容');
								} else if(arg2.code == 200) {
									// 发布成功效果
									let div = document.createElement('div');
									div.className = 'publish-suc';
									div.innerText = '发布成功';
									commentPublish.appendChild(div);
									setTimeout(() => {
										div.remove();
									}, 2000);
									// 添加求购信息
									let li = document.createElement('div');
									li.className = 'comment-item';
									let _time = new Date(arg2.data.time).format('yyyy-MM-dd HH:mm');
									li.innerHTML = `<div class="clearfix">
										<div class="item-l fl">
											<img src="${data.imgPath}" alt="用户头像" />
										</div>
										<div class="item-r fl">
											<span class="item-name">${data.nickname}</span>
											<span class="item-time">${_time}</span>
											<p class="item-content">${contentStr}</p>
											<div class="item-info">
											<span class="item-like">0</span>
											<span class="item-reply">0</span>
											</div>
										</div>
										</div>
										<div class="comment-more" style="display:none;">
										<div class="comment-publish clearfix">
										<div class="publish-l">
											<img src="${data.imgPath}" alt="用户头像" />
										</div>
										<div class="publish-m">
											<textarea cols="80" name="msg" rows="5" placeholder="回复 @${data.nickname}："></textarea>
										</div>
										<button class="publish-submit">发表评论</button>
										</div>
										<div class="comment-reply clearfix">
										<ul>
										</ul>
										</div>
										</div>`;
									// 在最前面加入
									if(commentArea.children.length == 0) {
										commentArea.appendChild(li);
									} else {
										commentArea.insertBefore(li,commentArea.children[0]);
									}
									// 给点赞和回复注册事件
									li.querySelector('.item-like').onclick = function() {
										likeButtonEvent.call(this,arg2.data.wid);
									}
									li.querySelector('.item-reply').onclick = function() {
										replyButtonEvent.call(this,arg2.data.wid);
									};
								}
							}
						});
					}
				}	
			} else {
				// 未登录
				userBar1.innerHTML = `<a href="/page/user/login.html">你好，请登录</a>`;
				userBar2.innerHTML = `<a class="ht" href="/page/user/regist.html">立即注册</a>`;
			}
		}
	});
}
//请求求购信息
let sback = location.search;
let wd = '';
if(sback) {
	sback = sback.substring(1);
	let params = sback.split('&');
	params.forEach(item => {
		if(item.startsWith('wd=') && item.length > 3) {
			wd = decodeURI(item.split('=')[1]);
		}
	})
}
ajax({
	type: 'POST',
	url: '/want/getWants',
	async: true,
	data: {
		wd: wd
	},
	success: function(xhr) {
		let arg3 = JSON.parse(xhr.responseText);
		if(arg3.code == 200) {
			let wants = arg3.data;
			setWants(wants);
			// 按时间排序
			newSort.onclick = function() {
				let className = this.className;
				let index;
				if((index = className.indexOf(' on')) == -1) {
					let chooseBar = hotSort.nextElementSibling;
					hotSort.className = hotSort.className.substring(0, 10);
					this.className = this.className + ' on';
					chooseBar.style.left = '0';
					removeAllChildren(commentArea);
					wants = wants.sort((a, b) =>  b.time - a.time);
					setWants(wants);
				}
			}
			hotSort.onclick = function() {
				let className = this.className;
				let index;
				if((index = className.indexOf(' on')) == -1) {
					let chooseBar = hotSort.nextElementSibling;
					newSort.className = newSort.className.substring(0, 10);
					this.className = this.className + ' on';
					chooseBar.style.left = '103px';
					removeAllChildren(commentArea);
					wants = wants.sort((a, b) =>  {
						if(b.likeCount == a.likeCount) {
							return b.time - a.time;
						}
						return b.likeCount - a.likeCount;
					});
					setWants(wants);
				}
			}
		}
		
	}
	
});
// 请求活跃用户
ajax({
	type: 'POST',
	url: '/want/activeUser',
	async: true,
	success: function(xhr) {
		let arg = JSON.parse(xhr.responseText);
		if(arg.code == 200) {
			let users = arg.data;
			// 设置活跃用户
			let activeUl = commentPublish.parentNode.nextElementSibling.children[1];
			users.forEach(aUser => {
				let li = document.createElement('li');
				li.innerHTML = `<img src="${aUser.imgPath}" alt="用户头像" />
					<span>${aUser.nickname}</span>`;
				activeUl.appendChild(li);				
			});
		}
	}
});

/*
 * 	添加求购信息
 * 	参数1：留言集合
 * 
 * */
function setWants(wants) {
	wants.forEach(want => {
		// 添加求购信息
		let div = document.createElement('div');
		div.className = 'comment-item';
		let _time = new Date(want.time).format('yyyy-MM-dd');
		let _imgPath = '/images/face/default.jpg';
		div.innerHTML = `<div class="clearfix">
							<div class="item-l fl">
								<img src="${want.user.imgPath}" alt="用户头像" />
							</div>
							<div class="item-r fl">
								<span class="item-name">${want.user.nickname}</span>
								<span class="item-time">${_time}</span>
								<p class="item-content">${want.content}</p>
								<div class="item-info">
									<span class="item-like">${want.likeCount}</span>
									<span class="item-reply">${want.replyCount}</span>
								</div>
							</div>
						</div>
						<div class="comment-more" style="display:none;">
							<div class="comment-publish clearfix">
								<div class="publish-l">
									<img src="${_imgPath}" alt="用户头像" />
								</div>
								<div class="publish-m">
									<textarea cols="80" name="msg" rows="5" placeholder="回复 @${want.user.nickname}："></textarea>
								</div>
								<button class="publish-submit">发表评论</button>
							</div>
							<div class="comment-reply clearfix">
								<ul>
								</ul>
							</div>
						</div>`;
		commentArea.appendChild(div);
		// 给点赞和回复注册事件
		div.querySelector('.item-like').onclick = function() {
			likeButtonEvent.call(this, want.wid);
		}
		div.querySelector('.item-reply').onclick = function() {
			replyButtonEvent.call(this, want.wid);
		};
	});
}


/*
	功能：留言板获取焦点事件
*/
function focusEvent() {
	this.style.borderColor = '#549ec5';
}
/*
	功能：留言板失去焦点事件
*/
function blurEvent() {
	this.style.borderColor = '#e5e9ef';
}
/* 留言区域效果 */
/*let commentLikes = commentArea.querySelectorAll('.item-like');
let replyButtons = commentArea.querySelectorAll('.item-reply');*/

/*
	功能：点击点赞按钮事件
	参数1：求购信息id
*/
function likeButtonEvent(id) {
	let _this = this;
	if(this.style.background.indexOf('click') == -1) {
		ajax({
			type: 'POST',
			url: '/want/like',
			async: true,
			data: {
				id: id,
			},
			success: function(xhr) {
				let arg = JSON.parse(xhr.responseText);
				if(arg.code == 200) {
					_this.style.background = 'url(/images/like_click_icon.png) no-repeat';
					let count = Number(_this.innerText);
					_this.innerText = count + 1;
				} else if(arg.code == 3020) {
					toast('请先登录');
				} else {
					toast('系统繁忙，请刷新页面后重试');
					setTimeout(() => {
						location.reload(true);
					}, 3000);
				}
			}
		});
	}
}
/*
	功能：点击评论按钮事件
*/
function replyButtonEvent(id) {
	// 设置评论图标
	if(!this.style.backgroundImage || this.style.backgroundImage == 'url("/images/message_icon.png")') {
		this.style.background = 'url(/images/message_blue_icon.png) no-repeat';
	} else {
		this.style.background = 'url(/images/message_icon.png) no-repeat';
	}
	let publish = this.parentNode.parentNode.parentNode.nextElementSibling;
	let button = publish.querySelector('button');
	let _this = this;
	if(publish.style.display.indexOf('none') != -1) {
		publish.style.display = 'block';
		let commentReply = publish.children[1];
		let commentReplyUl = commentReply.children[0];
		if(!data) {
			// 未登录
			let publishM = publish.children[0].children[1];
			removeAllChildren(publishM);
			let div = document.createElement('div');
			div.className = 'publish-login-wrap';
			div.innerHTML = `请先<a class="publish-tologin" href="/page/user/login.html" target="_blank">登录</a>后发表评论(・ω・)`;
			publishM.appendChild(div);
			button.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;';
		} else {
			// 添加用户头像
			publish.querySelector('img').src = data.imgPath;
			let textarea = publish.querySelector('textarea');
			textarea.onfocus = focusEvent;
			textarea.onblur = blurEvent; 
			textarea.focus();
			button.onclick = function() {
				let contentStr = textarea.value.trim();
				if(contentStr.length > 0 && button.innerText != '发送中') {
					console.log(contentStr);
					ajax({
						type: 'POST',
						url: '/reply/addByWant',
						async: true,
						data: {
							id: id,
							content: encodeURIComponent(contentStr)
						},
						beforeSend: function() {
							button.style = 'background-color: #e5e9ef;cursor: default;color: #b8c0cc;padding: 0;';
							button.innerText = '发送中';
							textarea.disabled = 'disabled';
						},
						success: function(xhr) {
							// 还原之前的效果
							button.style = '';
							button.innerText = '发表评论';
							textarea.disabled = '';
							// 清空留言板的内容
							textarea.value = '';
							let arg = JSON.parse(xhr.responseText);
							if(arg.code == 3400) {
								toast('系统繁忙，请刷新页面后重试');
								setTimeout(() => {
									location.reload(true);
								}, 3000);
							} else if(arg.code == 3020) {
								location.href = '/page/user/login.html';
							} else if(arg.code == 300) {
								toast('请输入评论内容');
							} else if(arg.code == 200) {
								// 发布成功效果
								let div = document.createElement('div');
								div.className = 'publish-suc';
								div.innerText = '发布成功';
								publish.appendChild(div);
								setTimeout(() => {
									div.remove();
								}, 2000);
								// 添加回复
								if(commentReply.style.display == 'none') {
									commentReply.style.display = 'block';
								}
								let li = document.createElement('li');
								li.className = 'clearfix';
								let _time = new Date(arg.data.time).format('yyyy-MM-dd HH:mm');
								li.innerHTML = `<div class="content-img">
													<img src="${data.imgPath}" alt="用户头像" />
												</div>
												<div class="content-main">
													<span class="content-name">${data.nickname}</span>
													<p>${contentStr}</p>
													<div class="content-b">
														<span class="content-time">${_time}</span>
														<span class="content-delete">删除</span>
													</div>
												</div>`;
								if(commentReplyUl.children.length == 0) {
									commentReplyUl.appendChild(li);
								} else {
									commentReplyUl.insertBefore(li, commentReplyUl.children[0]);
								}
								// 回复数加1
								let count = Number(_this.innerText);
								_this.innerText = count + 1;
								// 设置点击删除事件
								li.querySelector('.content-delete').onclick = function() {
									// 这里未做删除提示
									ajax({
										type: 'POST',
										url: '/reply/deleteByWant',
										async: true,
										data: {
											id1: arg.data.rid,
											id2: id
										},
										success: function(xhr) {
											let arg2 = JSON.parse(xhr.responseText);
											if(arg2.code == 3400) {
												toast('系统繁忙，请刷新页面后重试');
												setTimeout(() => {
													location.reload(true);
												}, 3000);
											} else if(arg2.code == 3020) {
												location.replace('/page/user/login.html');
											} else if(arg2.code == 200) {
												removeWorld(li);
												toast('删除成功', '#84cc77');
												let count = Number(_this.innerText);
												_this.innerText = count - 1;
											}
										}
									});
								}
							}
						}
					});
				}	
			}
		}
		// 请求回复信息
		let loadingDiv = document.createElement('div');
		ajax({
			type: 'POST',
			url: '/reply/findReplys',
			async: true,
			data: {
				id: id
			},
			beforeSend: function() {
				loadingDiv.style = 'margin: 0 0 22px 90px;color: #aaa;font-family: fangsong;font-size: 16px;';
				loadingDiv.innerText = 'loading...';
				publish.appendChild(loadingDiv);
				removeAllChildren(commentReplyUl);
			},
			success: function(xhr) {
				loadingDiv.remove();
				let arg3 = JSON.parse(xhr.responseText);
				if(arg3.code == 200) {
					let replys = arg3.data;
					if(replys) {
						replys.forEach(reply => {
							let replyLi = document.createElement('li');
							replyLi.className = 'clearfix';
							let _time = new Date(reply.time).format('yyyy-MM-dd HH:mm');
							replyLi.innerHTML = `<div class="content-img">
												<img src="${reply.user.imgPath}" alt="用户头像" />
											</div>
											<div class="content-main">
												<span class="content-name">${reply.user.nickname}</span>
												<p>${reply.content}</p>
												<div class="content-b">
													<span class="content-time">${_time}</span>
												</div>
											</div>`;
							if(data && reply.user.uid == data.uid) {
								let deleteSpan = document.createElement('span');
								deleteSpan.className = 'content-delete';
								deleteSpan.innerText = '删除';
								replyLi.querySelector('.content-b').appendChild(deleteSpan);
								// 点击删除事件
								deleteSpan.onclick = function() {
									// 这里未做删除提示
									ajax({
										type: 'POST',
										url: '/reply/deleteByWant',
										async: true,
										data: {
											id1: reply.rid,
											id2: id
										},
										success: function(xhr) {
											let arg2 = JSON.parse(xhr.responseText);
											if(arg2.code == 300) {
												toast('系统繁忙，请刷新页面后重试');
												setTimeout(() => {
													location.reload(true);
												}, 3000);
											} else if(arg2.code == 3020) {
												location.replace('/page/user/login.html');
											} else if(arg2.code == 200) {
												removeWorld(replyLi);
												toast('删除成功', '#84cc77');
												// 回复数减1
												let count = Number(_this.innerText);
												_this.innerText = count - 1;
											}
										}
									});
								}
							}
							commentReplyUl.appendChild(replyLi);
						});
					}
				} else {
					toast('系统繁忙，请刷新页面后重试');
					setTimeout(() => {
						location.reload(true);
					}, 3000);
				}
			}
		});
	} else {
		publish.style.display = 'none';
		button.onclick = null;
	}
}